#!/bin/sh

#没有参数直接退出
if [ -z $1 ]; then
  echo "parameter is NULL."
  exit 0
fi

#获取指定软件的进程号
PID_EXIST=$(pidof $1)

#软件名称第一个字符用 [] 包含，为了过滤grep进程
#改进后 使用进程号过滤，不需要这个处理了
PIDNAME=`echo $1`
#PIDNAME_HEAD=${PIDNAME:0:1}
#PIDNAME_TAIL=${PIDNAME:1:${#PIDNAME}}
#PIDNAME_TEMP="["${PIDNAME_HEAD}"]"${PIDNAME_TAIL}

#软件正在执行，则显示进程信息
if [ -n "$PID_EXIST" ]; then
  logger -t ${PIDNAME} "$1 is running."
  echo
  for PID in $PID_EXIST
  do
    #按照进程号过滤进程详细信息，仅显示第一行以去掉grep进程
    ps | grep $PID | sed -n '1p'
  done
  exit 0
fi

case $PIDNAME in 
"rsync")
  echo "$1 is finished."
  #设置rsync密码，实现rsync免密同步。NAS上设置rsync用户 any:ZGHcpt123

  export RSYNC_PASSWORD=ZGHcpt123
  
  RUN_NUM=$(cat $2)
  echo $RUN_NUM
	case $RUN_NUM in 
		0)
			logger -t rsync "rsync AudioBook Start."
			rsync -avH --progress --delete any@10.10.10.35::homes/any/audiobook/ /mnt/media/audiobook/ && (logger -t rsync "rsync AudioBook NAS->OpenWrt OK!") || (logger -t rsync "rsync AudioBook NAS->OpenWrt Fail!";exit 1)
#			if [ $? -eq 0 ];then
#				logger -t rsync "rsync AudioBook NAS->OpenWrt OK!"
#			else
#				logger -t rsync "rsync AudioBook NAS->OpenWrt Fail!"
#			fi
			RUN_NUM=$((RUN_NUM+1))
			;;
		1)
			logger -t rsync "rsync Music Start."
			rsync -avH --progress --delete any@10.10.10.35::Media/Music/ /mnt/media/music/ && (logger -t rsync "rsync Music NAS->OpenWrt OK!") || (logger -t rsync "rsync Music NAS->OpenWrt Fail!";exit 1)
#			if [ $? -eq 0 ];then
#				logger -t rsync "rsync Music NAS->OpenWrt OK!"
#			else
#				logger -t rsync "rsync Music NAS->OpenWrt Fail!"
#			fi
			RUN_NUM=$((RUN_NUM+1))
			;;
		2)
			logger -t rsync "rsync Books Start."
			rsync -avH --progress --delete any@10.10.10.35::docker/calibre-web/books/ /mnt/media/books/ && (logger -t rsync "rsync Books NAS->OpenWrt OK!") || (logger -t rsync "rsync Books NAS->OpenWrt Fail!";exit 1)
#			if [ $? -eq 0 ];then
#				logger -t rsync "rsync Books NAS->OpenWrt OK!"
#			else
#				logger -t rsync "rsync Books NAS->OpenWrt Fail!"
#			fi
			RUN_NUM=0
			;;
		*)
			RUN_NUM=0
			;;
	esac
	echo $RUN_NUM>$2
  ;;
"find")
  echo "$1 is finished."
  ;;
*)
  echo "$1 not found."
  ;;
esac

exit 0
